/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 *
 */

import { FileSet } from '@ohos/hvigor';
import fse from 'fs-extra';
import path from 'path';

import { DefaultTargetConst } from '../../const/common-const.js';
import { ToolChainsConst } from '../../const/sdk-const.js';
import { CodeType } from '../../enum/code-type-enum.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { OhosHapTask } from '../task/ohos-hap-task.js';

const ohosTestTargetName = DefaultTargetConst.OHOS_TEST_TARGET;

/**
 * 将编译完的ets和js复制到同一个目录下
 */
export class MergeNodeAssets extends OhosHapTask {
  private readonly intermediatesOutPath: string;
  private readonly intermediatesAssetsPath: string;
  private _log = OhosLogger.getLogger(MergeNodeAssets.name);

  constructor(targetService: TargetTaskService) {
    super(targetService, TaskNames.LegacyFATask.MERGE_NODE_ASSETS);
    this.intermediatesOutPath = this.pathInfo.getInterMediatesLoaderOutPath();
    this.intermediatesAssetsPath = path.resolve(this.pathInfo.getIntermediatesFaAssetsPath(this.targetData.getProduct()), CodeType.JS);
  }

  declareInputFiles(): FileSet {
    const fileSet = new FileSet();
    const etsCodeModel = this.moduleModel.getSourceSetByTargetName(this.targetName).getCodeMap().get(CodeType.ETS);
    const jsCodeModel = this.moduleModel.getSourceSetByTargetName(this.targetName).getCodeMap().get(CodeType.JS);
    if ((etsCodeModel || jsCodeModel) && this.targetData.hasRichDeviceInTarget()) {
      fileSet.addEntry(this.intermediatesOutPath, { isDirectory: true });
    }
    return fileSet;
  }

  declareOutputFiles(): FileSet {
    return new FileSet().addEntry(this.intermediatesAssetsPath, { isDirectory: true });
  }

  protected beforeTask() {
    fse.removeSync(this.intermediatesAssetsPath);
  }

  protected doTaskAction(): void {
    const options = {
      filter(src: string) {
        const stats = fse.statSync(src);
        /**
         * 不拷贝js文件，任务当前只有富设备会走。
         * 对于瘦设备：
         *   无论是release还是debug，都不能删除js文件，否则js产物丢失会造成运行时异常，安全风险已评估。
         * 对于富设备：
         *   debug模式下会生成js，需要删除，release模式下，不会生成js，此处逻辑暂不区分debug还是release。
         */
        return !(stats.isFile() && src.endsWith('.js'));
      }
    };

    const etsAssets = path.resolve(this.intermediatesOutPath, CodeType.ETS);
    if (fse.existsSync(etsAssets)) {
      fse.copySync(etsAssets, this.intermediatesAssetsPath, options);
    }

    const jsAssets = path.resolve(this.intermediatesOutPath, CodeType.JS);
    if (fse.existsSync(jsAssets)) {
      fse.copySync(jsAssets, this.intermediatesAssetsPath, options);
    }
  }

  initTaskDepends(): void {
    const useRollupETS = fse.existsSync(path.resolve(this.sdkInfo.getEtsLoader(), ToolChainsConst.ROLL_UP_CONFIG_FILE));
    const useRollupJS = fse.existsSync(path.resolve(this.sdkInfo.getJsLoader(), ToolChainsConst.ROLL_UP_CONFIG_FILE));
    this._log.debug(useRollupETS ? 'compile ArkTS with rollup' : 'compile ArkTS with webpack');
    this._log.debug(useRollupJS ? 'compile ace js with rollup' : 'compile ace js with webpack');
    if (this.targetName === ohosTestTargetName) {
      this.declareDepends(useRollupETS ? 'LegacyOhosTestCompileArkTS' : 'LegacyOhosTestBuildArkTS');
      this.declareDepends(useRollupJS ? 'LegacyOhosTestCompileJS' : 'LegacyOhosTestBuildJS');
    } else {
      this.declareDepends(useRollupETS ? 'LegacyCompileArkTS' : 'LegacyBuildArkTS');
      this.declareDepends(useRollupJS ? 'LegacyCompileJS' : 'LegacyBuildJS');
    }
  }
}
